package com.atguigu.gmall.activity.receiver;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class SeckillReceiver {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    /**
     * 扫描数据库将秒杀商品存入缓存
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_1, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = {MqConst.ROUTING_TASK_1}
    ))
    public void importItemToRedis(Message message, Channel channel) {

        // 查询数据库是否有秒杀商品--->秒杀商品放入redis--->秒杀商品的数量放入redis--->初始化状态位

        // 查询数据库是否有秒杀商品
        // status = 1 && stock_count > 0 && start_time == new Date()
        QueryWrapper<SeckillGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).gt("stock_count", 0);
        queryWrapper.eq("DATE_FORMAT(start_time,'%Y-%m-%d')", DateUtil.formatDate(new Date()));
        List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(queryWrapper);

        // 循环遍历
        for (SeckillGoods seckillGoods : seckillGoodsList) {

            // 准备将秒杀商品放入缓存 需要先判断缓存中是否有该秒杀商品
            Boolean isExist = redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).hasKey(seckillGoods.getSkuId().toString());
            if (isExist) {
                continue;
            }

            // 将秒杀商品放入缓存 使用 hash(key,field,value) 存储数据
            redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).put(seckillGoods.getSkuId().toString(), seckillGoods);

            // 秒杀商品的数量放入 redis 使用 list 存储数据 将每个商品数量存入 list
            for (Integer i = 0; i < seckillGoods.getStockCount(); i++) {
                redisTemplate
                        .boundListOps(RedisConst.SECKILL_STOCK_PREFIX + seckillGoods.getSkuId().toString())
                        .leftPush(seckillGoods.getSkuId().toString());
            }
            //初始化状态位
            redisTemplate.convertAndSend("seckillpush", seckillGoods.getSkuId() + ":1");
        }

        // 手动确认ACK
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 监听秒杀用户队列
     *
     * @param userRecode
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_SECKILL_USER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_SECKILL_USER),
            key = {MqConst.ROUTING_SECKILL_USER}
    ))
    public void seckill(UserRecode userRecode, Message message, Channel channel) {
        if (userRecode != null) {
            // 预下单
            seckillGoodsService.seckillOrder(userRecode.getUserId(), userRecode.getSkuId());
        }
        // 手动确认ACK
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
